// pages/signup/signup.js
import { request } from "../../request/index.js"
import { navigateTo, showToast,startBeaconDiscovery } from "../../utils/asyncWx.js"
import { isNotEmptyStr } from "../../utils/util.js"
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    eventid: "",
    opengid: "",
    event: {},
    beaconos: {},
    promptText: "请点击打卡按钮"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {

    // 判断是否输入个人信息，没有则跳转到用户信息录入界面
    let avatarUrl = wx.getStorageSync('avatarUrl')
    if(!isNotEmptyStr(avatarUrl)){
      navigateTo({url:"/pages/fillInfo/fillInfo"})
    }
    
    console.log(options)
    this.setData({ eventid: options.eventid, opengid: options.opengid })

    // let openid = wx.getStorageSync("openid");
    // console.log("event_detail openid:>>>>> ",openid);
    let data = {eventid: options.eventid}
    // 根据eventid 查询事件详情
    const res = await request({url: "/AttendanceEvent/getEvent",data})
    let event = res.data.data
    console.log(event);
    this.setData({event})
  },
  // 打卡
  async check() {
    console.log("check start!")
    // 判断opengid与事件是否一致
    if(this.data.event.opengid!=this.data.opengid){
      await showToast({title: "不是该事件的打卡群成员，无法打卡"})
      return
    } 

    // 更改提示语
    this.setData({promptText:"打卡条件检测中……"})

    // 搜索附近的beacons、监听beacon更新、打卡判断、成功反馈
    await this.startBeaconDiscovery()

  },
  // 开始搜索附近的beacon设备   Promise 改良版
  async startBeaconDiscovery() {
    console.log("startBeaconDiscovery start!")
    if(this.data.event==null){
      console.log("没有event")
      return
    }
    let {beacon} = this.data.event
    const res = await startBeaconDiscovery().catch(err => console.log(err))
    console.log("startBeaconDiscovery success: ", res)
    // 注册Beacon设备更新监听事件
    wx.onBeaconUpdate((res1) => {
      console.log(res1);
      this.setData({
        beacons: res1.beacons
      })
      res1.beacons.forEach(async(item)=>{
        // 检测beacon参数是否一致
        if(item.uuid.toLowerCase() === beacon.uuid
          && item.major === beacon.major
          && item.minor === beacon.minor
          ){

            console.log("可以打卡")
            // 隐藏加载条
            wx.hideNavigationBarLoading()
            // 卸载所有监听函数
            wx.offBeaconUpdate()
            console.log("卸载所有监听函数")

            // 搜索到 即可以打卡
            const result = await this.signUp()
            // 判断打卡是否成功   成功则告知用户
            if(result.data.data==1){
              wx.showToast({title: "打卡成功"})
            }

            this.setData({promptText:"打卡成功！"})
            
            return
          }else{
            console.log("不能打卡")
          }
      })
      // 打卡失败
      wx.showToast({title: "暂未搜索到可用beacon"})
    })
  },


  // 执行打卡
  async signUp(){
    console.log("signUp start!")
    let data = {
      opengid: this.data.opengid,
      eventid: this.data.eventid,
    }
    let header = { "Content-Type": "application/x-www-form-urlencoded" }
    const res =  await request({url:"/EventUser/signUp",data,header,method:"POST"})
    console.log("signUp:>>>>> ",res);
    return res
  }
})